import { Outlet, useLocation, useNavigate } from "react-router-dom";
import withAuth from "../components/withAuth";
import { NavBar, Tabbar } from "react-vant";
import "./MyLayout.css";
import {
  ArrowLeft,
  BarChartO,
  HomeO,
  ManagerO,
  ShopO,
} from "@react-vant/icons";
import { useEffect, useState } from "react";
import { matchRoute, stringIsSame, stringStartWith } from "@/utils/common";
import routes from "@/router/routes";

const paths = ["/", "/chat", "/good", "/my"];

const MyLayout: React.FC = () => {
  const location = useLocation();
  const [value, setValue] = useState(0);
  const [title, setTitle] = useState("");
  const navigate = useNavigate();

  useEffect(() => {
    const path = location.pathname;
    const route = matchRoute(path, routes);
    setTitle(route.title);
    if (path === "/") {
      setValue(0);
    } else {
      setValue(
        paths.findIndex((d, i) => i !== 0 && stringStartWith(path, d, true))
      );
    }
  }, [location.pathname]);

  const handleTabbarChange = (active: string | number) => {
    if (value === active) {
      return;
    }
    navigate(paths[active as number]);
  };

  return (
    <>
      <div className="my-layout-container">
        <NavBar
          title={title}
          fixed
          placeholder
          leftArrow={paths.includes(location.pathname) ? null : <ArrowLeft />}
          leftText={paths.includes(location.pathname) ? null : "返回"}
          onClickLeft={() => navigate(-1)}
        />
        <Outlet />
        <Tabbar value={value} placeholder onChange={handleTabbarChange}>
          <Tabbar.Item icon={<HomeO />}>首页</Tabbar.Item>
          <Tabbar.Item icon={<BarChartO />}>图表</Tabbar.Item>
          <Tabbar.Item icon={<ShopO />}>商品</Tabbar.Item>
          <Tabbar.Item icon={<ManagerO />}>我的</Tabbar.Item>
        </Tabbar>
      </div>
    </>
  );
};

export default withAuth(MyLayout);
